package rpc;

import com.rabbitmq.client.*;
import constant.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-09-19
 * @time: 11:01:46
 */
public class RPCClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1. 创建 channel
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();


        // 2. 声明队列
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE_NAME, true, false, false, null);

        // 3. 发送消息
        // 3.1 设置消息的属性
        // 唯一标志本次请求
        String corrId = UUID.randomUUID().toString();
        // 定义临时队列, 并返回生成队列的名字
        String replyQueueName = channel.queueDeclare().getQueue();
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties()
                .builder()
                .correlationId(corrId)  // 唯一标志本次请求
                .replyTo(replyQueueName) // 设置回调队列
                .build();
        String msg = "hello rpc ...";
        // 3.2 发送消息, 使用默认交换机
        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE_NAME,basicProperties,msg.getBytes());

        // 4. 处理回调结果
        // 4.1 阻塞队列, 用于存储回调结果
        final BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>(1);
        // 4.2 接受服务器响应
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接受到回调消息...: " + new String(body));
                // 判断消息的属性中 correlationId 和 之前设置的是否相等
                if (corrId.equals(properties.getCorrelationId())) {
                    // 存储回调结果
                    blockingQueue.offer(new String(body, StandardCharsets.UTF_8));
                }
            }
        };
        channel.basicConsume(replyQueueName,true,defaultConsumer);
        // 获取回调结果
        String result = blockingQueue.take();
        System.out.println("[RPCClient]: " + result);

        // 5. 释放资源
        channel.close();
        connection.close();
    }
}
